Remove leading zeros from an IP address¶
re.sub(r’b0+(d)’, r’1’, ip)
Remove leading zeros from an IP address.
Method:
Using a capture group, match the last digit and copy it and prevents
all the digits from being replaced.
d Matches any decimal digit, this is equivalent
to the set class [0-9].
b allows you to perform a “whole words only” search
using a regular expression in the form of bwordb
import re
def remove_lead_zeros(ip):
new_ip = re.sub(r'\b0+(\d)', r'\1', ip)
return new_ip
# test
ip = "100.020.003.400"
print(remove_lead_zeros(ip)) # 100.20.3.400
ip = "001.200.001.004"
print(remove_lead_zeros(ip)) # 1.200.1.4